<template>
	<div style="padding:0 37px 0 44px">
    <div class="breadcrumb-father">
      <div class="new-breadcrumb">
        
        <router-link  :to="{path:'/welcome'}">
          <img src="../../../assets/imgs/Home.png" alt="">
        </router-link>
          <span>{{$t('newcash.Withdrawal1')}}</span>
        <span class="arrow">></span>
          <span>{{$t('profit.profit')}}</span>
      </div>
    </div>

    <div class="card-table">
      <div class="card-table-title">
        <svg aria-hidden="true" class="svg-icon svg-title-icon">
              <use xlink:href="#icon-wallet"></use>
            </svg>
        <span>{{$t('profit.profit')}}</span>
      </div>

      <!--搜索输入框-->
      <div class="search">
        <div class="search-input">
          <div class="date-wrapper">
            <label for="">{{$t('profit.countDate')}}</label>
            <div class="date-line"></div>
            <el-date-picker :editable=false clearable value-format="yyyy-MM-dd" type="date" @keyup.enter.native="handleFilter(0)" v-model="searchData.startDate"></el-date-picker>
          </div>

          <div>
            <label for="">{{$t('other.EstablishmentTo')}}</label>
            <el-date-picker :editable=false clearable value-format="yyyy-MM-dd" type="date" @keyup.enter.native="handleFilter(0)" v-model="searchData.endDate"></el-date-picker>
          </div>

          <div>
            <label for="">{{$t('button.Merchant')}}</label>
            <el-input v-model="searchData.name" clearable :maxlength=100 @keyup.enter.native="handleFilter(0)"></el-input>
          </div>

          <div>
            <label for="">{{$t('trade.merchantNumber')}}</label>
            <el-input v-model="searchData.merchantNumber" clearable :maxlength=14 @keyup.enter.native="handleFilter(0)"></el-input>
          </div>

          <div v-if="userType === '8' ? false : true">
            <label for="">{{$t('newcash.agentName')}}</label>
            <el-input v-model="searchData.dName" clearable :maxlength=100 @keyup.enter.native="handleFilter(0)"></el-input>
          </div>

          <div v-if="userType === '2' ? false : true">
            <label for="">{{$t('salesman.Salesman')}}</label>
            <el-input v-model="searchData.salesmanName" clearable :maxlength=50 @keyup.enter.native="handleFilter(0)"></el-input>
          </div>

          <div class="search-btn-group">
            <el-button class="blue-btn mini2-btn" @click="handleFilter(0)">{{ $t('button.search') }}</el-button>
            <el-button class="blue-btn mini2-btn" @click="resetFilter">{{ $t('button.Reset') }}</el-button>
          </div>
        </div>
        
      </div>

      <div class="table-border">
        <div class="search-result-head">
          <span>{{ searchInfo }}</span>
          <span style="float:right;">
            <a href="javascript:void(0)" @click="export2Excel()" :title="$t('button.SaveResult')"><icon-svg icon-class="daochu"></icon-svg></a> 
            <a href="javascript:void(0)" @click="refresh()" :title="$t('button.Refresh')"><icon-svg icon-class="shuaxin" id="refresh_icon"></icon-svg></a>
          </span>
        </div>
        <el-table border :data="profitDatas" height=500 v-loading="loading" :element-loading-text="$t('button.loading')" element-loading-background="rgba(255, 255, 255, 1)">
          <el-table-column type="index" fixed :label="$t('index.Number')" width="80">
          </el-table-column>
          <el-table-column prop="settlementDate" :label="$t('profit.date')" width="140" show-overflow-tooltip>
          </el-table-column>
          <el-table-column prop="merchantName" :label="$t('button.Merchant')" width="180" show-overflow-tooltip>
          </el-table-column>
          <el-table-column prop="merchantNumber" :label="$t('trade.merchantNumber')" width="140">
          </el-table-column>
          <!-- <el-table-column prop="money" :label="$t('trade.Amount')" width="140" :formatter="judgeAmount">
          </el-table-column> -->
          <el-table-column prop="money" :label="$t('profit.payment')" width="200" :formatter="judgeAmount">
          </el-table-column>
          <el-table-column prop="refundMoney" :label="$t('profit.settlementDateRefund')" width="230" :formatter="judgeRefundMoney">
          </el-table-column>
          <el-table-column v-if="userType === '2' || userType === '8' ? false : true" prop="companyProfit" :label="$t('profit.acquirerFee')" width="140" :formatter="judgeAcquirerFee">
          </el-table-column>
          <el-table-column v-if="(userType === '2' || userType === '8') ? false : true" prop="channel" :label="$t('profit.channel')" width="100" :formatter="judgeChannel">
          </el-table-column>
          <el-table-column v-if="(userType === '2' || userType === '8') ? false : true" prop="wXProfit" :label="$t('profit.channelFee')" width="180" :formatter="judgeChannelFee">
          </el-table-column>
          <el-table-column v-if="userType === '8' ? false : true" prop="distributorName" :label="$t('agent.agent')" width="140">
          </el-table-column>
          <el-table-column v-if="userType === '8' ? false : true" prop="distribtorProfit" :label="$t('profit.agentComm')" width="140" :formatter="judgeAgentComm">
          </el-table-column>
          <el-table-column v-if="userType === '2' ? false : true" prop="salesmanName" :label="$t('salesman.Salesman')" width="140" :formatter="judgeSalesmanName" show-overflow-tooltip>
          </el-table-column>
          <el-table-column v-if="userType === '2' ? false : true" prop="salesmanProfit" :label="$t('profit.BDComm')" width="140" :formatter="judgeBDComm" show-overflow-tooltip>
          </el-table-column>
          <el-table-column v-if="(userType === '2' || userType === '8') ? false : true" prop="settlementMoney" :label="$t('profit.settlement')" width="180" :formatter="judgeSettlement">
          </el-table-column>
        </el-table>
      </div>
    </div>

    <div class="trade_money" v-show="showSum">
      <template v-if="(userType === '2' || userType === '8') ? false : true">
        <span>{{ $t('profit.acquirerFeeTotal') }}:</span>
        <span v-if="res.companySumProfit < 0"> -{{ currency }} {{res.companySumProfit | fMoneyFilter | fMoney}}</span>
        <span v-else> {{ currency }} {{res.companySumProfit | fMoney}}</span>
      </template>
      <template v-if="userType === '8' ? false : true">
        <span class="trade_money_span">{{ $t('profit.agentCommTotal') }}:</span>
        <span v-if="res.distribtorSumProfit < 0"> -{{ currency }} {{res.distribtorSumProfit | fMoneyFilter | fMoney}}</span>
        <span v-else>{{ currency }} {{res.distribtorSumProfit | fMoney}}</span>
      </template>
      <template v-if="userType === '2' ? false : true">
        <span class="trade_money_span">{{ $t('profit.BDCommTotal') }}:</span>
        <span v-if="res.salesmanSumProfit < 0"> -{{ currency }} {{res.salesmanSumProfit | fMoneyFilter | fMoney}}</span>
        <span v-else> {{ currency }} {{res.salesmanSumProfit | fMoney}}</span>
      </template>
    </div>

    <div class="pagination-container">
      <el-pagination @size-change="handleSizeChange" background @current-change="handleCurrentChange" :current-page.sync="searchData.page" :page-sizes="[15,20,30,50]" :page-size="searchData.pageSize" layout="total, sizes, prev, pager, next, jumper" :total="res.total"></el-pagination>
    </div>

  </div>
</template>
<script>
import { findProfit } from "api/profit/index";
import XLSX from "xlsx";
import XLSX_SAVE from "file-saver";

export default {
  name:'profit',
  data() {
    return {
      companyId:localStorage.getItem("companyId"),
      distributorId:localStorage.getItem("distributorId"),
      salesmanId:localStorage.getItem("salesmanId"),
      userType:localStorage.getItem("userType"),
      currency:undefined,
      //按条件搜索商户所需参数
      searchData: {
        startDate: null,
        endDate: null,
        name: null,
        merchantNumber: null,
        dName: null,
        salesmanName: null,
        page: 1,
        pageSize: 15
      },
      showSum: false,
      searchInfo:"",
      profitDatas:[],
      res: [],
      degIndex: 1,
      rorateFlag: true,
      exportSearchData:{},
      oldPage: null,
      loading: true,
    };
  },
  watch:{
    'searchData.page':function(newVal,oldVal){
        this.oldPage = oldVal;
    },
  },
  created() {
    this.getprofitList(this.searchData);
    this.searchInfo = this.$t('profit.profit');

    if (this.companyId == '1') this.currency = 'HK$ ';
    if (this.companyId == '2') this.currency = 'A$ ';
  },
  methods: {
    //获得商户列表的方法
    getprofitList(value,str) {
      value.companyId = this.companyId;

      // 根据角色类型传对应ID去获取列表数据
      if(this.userType === '2'){
        value.distributorId = this.distributorId;
      }else if(this.userType === '8'){
        value.salesmanId = this.salesmanId;
      }

      findProfit(value).then(res => {
          const _that = this;
          this.showSum = true;
          this.res = res.value;
          this.profitDatas = res.value.list;

          // 如果是分页触发，循环去除选中样式，对点击后的项数添加选中样式
          if( str == 'CurrentChange' ){
            let obj = $('.el-pager .number');
            for( let i = 0; i < obj.length; i++){
                if($(obj[i]).html() == this.searchData.page) {
                  $(obj[i]).addClass('active');
                } else {
                  $(obj[i]).removeClass('active');
                }
            }
          }

          setTimeout(function() {
            // 隐藏载入提示层
            _that.loading = false;
          },500)

        })
        .catch(error => {
          console.log(error);
        });
    },

    //按条件搜索的方法
    handleFilter(sign,str) {

      // 显示载入提示层
      this.loading = true;

      if(sign === 0) this.searchInfo =  this.$t('index.searchResults');
      //查询分润的参数
      $.extend(this.exportSearchData, this.searchData);
      this.formatObj(this.exportSearchData);
      this.getprofitList(this.exportSearchData,str);

      if( str == 'CurrentChange' ){
        // 获取所有分页项数，循环去除选中样式，对点击前的项数添加选中样式
        let obj = $('.el-pager .number');
        for( let i = 0; i < obj.length; i++){
            if($(obj[i]).html() == this.oldPage) {
              console.log(this.oldPage);
              $(obj[i]).addClass('active');
            } else {
              $(obj[i]).removeClass('active');
            }
        }
      }
    },

    //清空筛选条件
    resetFilter() {
      this.searchData.startDate = null;
      this.searchData.endDate = null;
      this.searchData.name = null;
      this.searchData.merchantNumber = null;
      this.searchData.dName = null;
      this.searchData.salesmanName = null;
      this.searchData.page = 1;
      this.searchData.pageSize=15;
      this.searchInfo = this.$t('profit.profit');
      this.handleFilter(1);
    },

    formatObj(obj) {
      let arr = Object.keys(obj);
      for (let i = 0; i < arr.length; i++) {
        if (obj[arr[i]] === "") {
          obj[arr[i]] = null;
        }
      }
    },

    //pageSize 改变时会触发
    handleSizeChange(val) {
      this.searchData.pageSize = val;
      this.handleFilter(1);
    },
    //currentPage 改变时会触发
    handleCurrentChange(val) {
      this.searchData.page = val;
      this.handleFilter(1,'CurrentChange');
    },

    export2Excel() {
      // let length = this.res.total;
      require.ensure([], () => {

        this.exportSearchData.companyId = this.companyId;

        // 根据角色类型传对应ID去获取列表数据
        if(this.userType === '2'){
          this.exportSearchData.distributorId = this.distributorId;
        }else if(this.userType === '8'){
          this.exportSearchData.salesmanId = this.salesmanId;
        }

        let listQuery = {};
        $.extend(listQuery, this.exportSearchData);
        listQuery.pageSize = this.res.total;
        findProfit(listQuery).then(res => {
          const list = res.value.list;
          const { export_json_to_excel } = require("../../../vendor/Export2Excel");

          for (let i = 0; i < list.length; i++) {
            list[i].money = this.fmoney(list[i].money,2);
            list[i].refundMoney = this.fmoney(list[i].refundMoney,2);
            list[i].companyProfit = this.fmoney(list[i].companyProfit,2);
            list[i].wXProfit = this.fmoney(list[i].wXProfit,2);
            list[i].distribtorProfit = this.fmoney(list[i].distribtorProfit,2);
            list[i].settlementMoney = this.fmoney(list[i].settlementMoney,2);
            list[i].channel = list[i].channel == "WX" ? this.$t('profit.wx') : "";

            if(list[i].salesmanName && list[i].merchantSalesmanName) {
              list[i].salesmanName = list[i].salesmanName + "," + list[i].merchantSalesmanName;
            }else if(!list[i].salesmanName && list[i].merchantSalesmanName) {
              list[i].salesmanName = list[i].merchantSalesmanName;
            }else {
              list[i].salesmanName = list[i].salesmanName;
            }

            if(list[i].salesmanProfit != undefined && list[i].merchantSalesmanProfit != undefined) {
              list[i].salesmanProfit = this.fmoney(list[i].salesmanProfit,2) + ", " + this.fmoney(list[i].merchantSalesmanProfit, 2);
            }else if(list[i].salesmanProfit == undefined) {
              list[i].salesmanProfit = this.fmoney(list[i].merchantSalesmanProfit, 2);
            }else {
              list[i].salesmanProfit = this.fmoney(list[i].salesmanProfit,2);
            }

          }

          let tHeader = [],
              filterVal = [];

          if(this.userType == 2) {
            // 当角色为代理商
            tHeader = [
              this.$t('profit.date'),
              this.$t('inputBox.merchantName'),
              this.$t('trade.merchantNumber'),
              this.$t('profit.payment') + ' ' + this.currency,
              this.$t('profit.settlementDateRefund') + ' ' + this.currency,
              this.$t('agent.agent'),
              this.$t('profit.agentComm') + ' ' + this.currency,
            ]; //对应表格输出的title
            filterVal = [
              "settlementDate",
              "merchantName",
              "merchantNumber",
              "money",
              "refundMoney",
              "distributorName",
              "distribtorProfit",
            ]; // 对应表格输出的数据
          }else if(this.userType == 8) {
            // 当角色为业务员
            tHeader = [
              this.$t('profit.date'),
              this.$t('inputBox.merchantName'),
              this.$t('trade.merchantNumber'),
              this.$t('profit.payment') + ' ' + this.currency,
              this.$t('profit.settlementDateRefund') + ' ' + this.currency,
              this.$t('salesman.Salesman'),
              this.$t('profit.BDComm') + ' ' + this.currency,
            ]; //对应表格输出的title
            filterVal = [
              "settlementDate",
              "merchantName",
              "merchantNumber",
              "money",
              "refundMoney",
              "salesmanName",
              "salesmanProfit",
            ]; // 对应表格输出的数据
          }else {
            tHeader = [
              this.$t('profit.date'),
              this.$t('inputBox.merchantName'),
              this.$t('trade.merchantNumber'),
              this.$t('profit.payment') + ' ' + this.currency,
              this.$t('profit.settlementDateRefund') + ' ' + this.currency,
              this.$t('profit.acquirerFee') + ' ' + this.currency,
              this.$t('profit.channel'),
              this.$t('profit.channelFee') + ' ' + this.currency,
              this.$t('agent.agent'),
              this.$t('profit.agentComm') + ' ' + this.currency,
              this.$t('salesman.Salesman'),
              this.$t('profit.BDComm') + ' ' + this.currency,
              this.$t('profit.settlement') + ' ' + this.currency,
            ]; //对应表格输出的title
            filterVal = [
              "settlementDate",
              "merchantName",
              "merchantNumber",
              "money",
              "refundMoney",
              "companyProfit",
              "channel",
              "wXProfit",
              "distributorName",
              "distribtorProfit",
              "salesmanName",
              "salesmanProfit",
              "settlementMoney",
            ]; // 对应表格输出的数据
          }

          const data = this.formatJson(filterVal, list);
          export_json_to_excel(tHeader, data, this.$t('profit.profit')); //对应下载文件的名字
        });
      });
    },

    refresh() {
      const _that = this;
      if(this.rorateFlag){
        document.getElementById('refresh_icon').style.transform = 'rotate('+ this.degIndex * 360 +'deg)';
        this.handleFilter(1);
        this.rorateFlag = false;
        setTimeout(function (param) { _that.rorateFlag = true;_that.degIndex++; },1000);
      }
    },

    // 合并业务员
    judgeSalesmanName(row) {
      if(row.salesmanName && row.merchantSalesmanName){
        return row.salesmanName + ", " + row.merchantSalesmanName;
      }else if(!row.salesmanName && row.merchantSalesmanName) {
        return row.merchantSalesmanName;
      }else if(row.salesmanName && !row.merchantSalesmanName){
        return row.salesmanName;
      }else {
        return "-";
      }
    },

    // 格式化合并业务员
    judgeBDComm(row) {
      
      let salesmanName = row.salesmanName; // 代理商业务员
      let merchantSalesmanName = row.merchantSalesmanName; // 商户业务员

      let salesmanProfit = row.salesmanProfit; // 代理商业务员分润
      let merchantSalesmanProfit = row.merchantSalesmanProfit; // 商户业务员分润
      // console.log("代理商业务员：" + salesmanName + "；商户业务员：" + merchantSalesmanName);
      if(salesmanName && merchantSalesmanName) {

        if(salesmanProfit < 0) {
          salesmanProfit = "-" + this.currency + this.fmoney(Math.abs(salesmanProfit),2);
        }else {
          salesmanProfit = this.currency + this.fmoney(salesmanProfit,2);
        }

        if(merchantSalesmanProfit < 0) {
          merchantSalesmanProfit = "-" + this.currency + this.fmoney(Math.abs(merchantSalesmanProfit),2);
        }else {
          merchantSalesmanProfit = this.currency + this.fmoney(merchantSalesmanProfit,2);
        }

        return salesmanProfit + ", " + merchantSalesmanProfit;
      }else if(merchantSalesmanName) {

        if(merchantSalesmanProfit < 0) {
          merchantSalesmanProfit = "-" + this.currency + this.fmoney(Math.abs(merchantSalesmanProfit),2);
        }else {
          merchantSalesmanProfit = this.currency + this.fmoney(merchantSalesmanProfit,2);
        }

        return merchantSalesmanProfit;
      }else if(salesmanName){
        if(salesmanProfit < 0) {
          salesmanProfit = "-" + this.currency + this.fmoney(Math.abs(salesmanProfit),2);
        }else {
          salesmanProfit = this.currency + this.fmoney(salesmanProfit,2);
        }

        return salesmanProfit;
      }else {
        return "-";
      }
    },

    //格式化金额
    judgeAmount(row) {
      let formatMoney = row.money;
      return (formatMoney = this.currency + this.fmoney(formatMoney, 2));
    },

    //格式化结算日退款
    judgeRefundMoney(row) {
      let formatRefundMoney = row.refundMoney;
      if(formatRefundMoney < 0) {
        formatRefundMoney = Math.abs(formatRefundMoney);
        return (formatRefundMoney = "-" + this.currency + this.fmoney(formatRefundMoney, 2));
      }else {
        return (formatRefundMoney = this.currency + this.fmoney(formatRefundMoney, 2));
      }
    },

    judgeAcquirerFee(row) {
      let formatMoney = row.companyProfit;
      if(formatMoney < 0) {
        formatMoney = Math.abs(formatMoney);
        return (formatMoney = "-" + this.currency + this.fmoney(formatMoney, 2));
      }else {
        return (formatMoney = this.currency + this.fmoney(formatMoney, 2));
      }
    },

    judgeChannelFee(row) {
      let formatMoney = row.wXProfit;
      if(formatMoney < 0) {
        formatMoney = Math.abs(formatMoney);
        return (formatMoney = "-" + this.currency + this.fmoney(formatMoney, 2));
      }else {
        return (formatMoney = this.currency + this.fmoney(formatMoney, 2));
      }
    },

    judgeAgentComm(row) {
      let formatMoney = row.distribtorProfit;
      if(formatMoney < 0) {
        formatMoney = Math.abs(formatMoney);
        return (formatMoney = "-" + this.currency + this.fmoney(formatMoney, 2));
      }else {
        return (formatMoney = this.currency + this.fmoney(formatMoney, 2));
      }
    },

    judgeSettlement(row) {
      let formatMoney = row.settlementMoney;
      if(formatMoney < 0) {
        formatMoney = Math.abs(formatMoney);
        return (formatMoney = "-" + this.currency + this.fmoney(formatMoney, 2));
      }else {
        return (formatMoney = this.currency + this.fmoney(formatMoney, 2));
      }
    },

    // 格式化渠道
    judgeChannel(row) {
      let channel = row.channel;
      return (channel === "WX" ? this.$t('profit.wx') : "");
    },

    // 格式化金额
    fmoney(s, n) {
      if( s === "" || s === undefined ) return s = "0.00";
      s = s / 100;
      n = n > 0 && n <= 20 ? n : 2;
      s = parseFloat((s + "").replace(/[^\d\.-]/g, "")).toFixed(n) + "";
      var l = s.split(".")[0].split("").reverse(),
      r = s.split(".")[1];
      let t = "";
      for (let i = 0; i < l.length; i++) {
        t += l[i] + ((i + 1) % 3 == 0 && i + 1 != l.length ? "," : "");
      }
      return (
        t.split("").reverse().join("") + "." + r
      );
    },

    // 格式化负数
    fmoney_abs(money) {
      if(money < 0) {
        return money = "-" + this.currency + this.fmoney(Math.abs(money),2);
      }else {
        return money;
      }
    },

    // 格式化数据
    formatJson(filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => v[j]));
    },

  },
};
</script>

<style lang="scss" scoped>
.trade_money{
  margin-top:10px;
  color:black;
  font-weight:bold;
  padding-left: 20px;
  font-style: italic;
  .trade_money_span{
    margin-left:30px;
  }
}
</style>
